# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, url_for, redirect, request
from qiniu import Auth, put_file, put_data, etag
from app import db
from models import Image
from flask_login import login_required
import time, datetime, os

access_key = 'vH5Lv8bdUabxnYZjlug2CENzTYhagsZZmpnycUH2'
secret_key = 'u5YfeU7Xg0EZDWWygWpPAYX_GHpLN1usIxb36tAq'
bucket_name = 'fangshiyue'

image = Blueprint('image', __name__, template_folder='templates')


@image.route('/')
@login_required
def index():
    images = Image.query.all()
    return render_template('image/index.html', images=images)


@image.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    if request.method == 'POST':
        f = request.files['file']
        img = Image()
        name, ext = os.path.splitext(f.filename)
        new_file = '%s%s' % (int(time.time()), ext)
        img.name = name
        img.key = upload_data(new_file, f.read())
        img.ext = ext[1:]
        db.session.add(img)
        db.session.commit()
        return redirect(url_for('image.index'))
    return render_template('image/upload.html')


def upload_file(key, local_file):
    auth = Auth(access_key, secret_key)
    token = auth.upload_token(bucket_name, key, 3600)
    ret, info = put_file(token, key, local_file)
    return ret['key']


def upload_data(key, data):
    auth = Auth(access_key, secret_key)
    token = auth.upload_token(bucket_name, key, 3600)
    ret, info = put_data(token, key, data)
    return ret['key']
